import { useEventListener } from '@vueuse/core'
import { nextTick, onMounted, ref, watch } from 'vue'

export default function useTableHeight () {
  const searchCollapse = ref('1')
  const element = ref<HTMLElement>()
  const yTable = ref<number>(0)
  watch(searchCollapse, handleComputedTableHeight)

  // toggle collapse
  function toggleCollapse () {
    searchCollapse.value = searchCollapse.value === '1' ? '0' : '1'
  }

  // event resize
  useEventListener(document.body, 'resize', handleComputedTableHeight)
  onMounted(handleComputedTableHeight)

  async function handleComputedTableHeight () {
    await nextTick()
    const el = element.value!
    const clientHeight = el.offsetHeight
    const searchHeight = searchCollapse.value ? (el.querySelector('.ms-table__search') as HTMLElement)!.offsetHeight : 0
    const toolsHeight = (el.querySelector('.ms-table__tools') as HTMLElement)!.offsetHeight
    const paginationHeight = (el.querySelector('.ms-table__pagination') as HTMLElement)!.offsetHeight
    const tableHeaderHeight = (el.querySelector('.ant-table-header') as HTMLElement)!.offsetHeight
    yTable.value = clientHeight - searchHeight - toolsHeight - paginationHeight - tableHeaderHeight - 20
  }

  return {
    element,
    yTable,
    searchCollapse,
    handleComputedTableHeight,
    toggleCollapse
  }
}
